<template>
  <ArtTableFullScreen>
    <div class="account-page" :style="{ height: containerMinHeight}" id="table-full-screen">
 	  <ArtRuleSearchForm 
			ref="dataSourceConfigSearchFormRef"
			rule="data-collector-query-form" 
			:showExpand="false"
			@reset="handleReset"
			@search="handleSearch"
	  ></ArtRuleSearchForm> 

      <ElCard shadow="never" class="art-table-card" style="height: calc(100vh - 214px);">
		<div style="height: calc(100% - 0px);">
			<ArtRuleTable 
				ref="dataSourceConfigTableRef"
				row-key="id"
				rule="data-collector-table" 
				:hideOnSinglePage="false"
				:fetch-data="fetchData" 
				:autoLoad="true"
				:customFormatters="customFormatters"
				:customToolBars="getToolBarFormatters"
				paginationAlign="right"
				></ArtRuleTable>
		</div>
      </ElCard>
	  
		
		<EditHttpDialog
		    v-model="httpDialog.visible"
		    :edit-data="httpDialog.data"
		    @submit="httpDialog"
		/>
		
		<EditMqttDialog
		    v-model="mqttDialog.visible"
		    :edit-data="mqttDialog.data"
		    @submit="handleSubmit"
		/>
		
		<WebSocketDialog
		    v-model="webSocketDialog.visible"
		    :edit-data="webSocketDialog.data"
		    @submit="handleSubmit"
		/>
		
		<DatabaseDialog
		    v-model="databaseDialog.visible"
		    :edit-data="databaseDialog.data"
		    @submit="handleSubmit"
		/>
		
		<EditExcelDialog
		    v-model="excelDialog.visible"
		    :edit-data="excelDialog.data"
		    @submit="handleSubmit"
		/>
		
		<EditKafkaDialog
		    v-model="kafkaDialog.visible"
		    :edit-data="kafkaDialog.data"
		    @submit="handleSubmit"
		/>
		
		<EditFtpDialog
		
		    v-model="ftpDialog.visible"
		    :edit-data="ftpDialog.data"
		    @submit="handleSubmit"
		/>
	  
	  
	  <EditHttpDrawer v-if="dialogVisible"  ref="editHttpDrawerRef" @closeDialog="handleDialogClosed"></EditHttpDrawer>
	  <EditMqttDrawer v-if="dialogVisible"  ref="editMqttDrawerRef" @closeDialog="handleDialogClosed"></EditMqttDrawer>
	  <EditDatabaseDrawer v-if="dialogVisible"  ref="editDatabaseDrawerRef" @closeDialog="handleDialogClosed"></EditDatabaseDrawer>
	  
	  
	  
	  <EditHikvisionHttpDrawer  ref="editHikvisionHttpDrawerRef" @closeDialog="handleDialogClosed"></EditHikvisionHttpDrawer>
<!-- 	  <HTTPDataProcessDrawer
	  	ref="httpDataProcessDrawerRef"
	  	@closeDialog="handleDialogClosed"
	  />
	  -->
	  
    </div>
  </ArtTableFullScreen>
</template>

<script setup lang="ts">
  import { h } from 'vue'
  import { ElDialog, FormInstance, ElTag } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import EditHttpDialog from './widgets/EditHttpDialog.vue'
  import EditMqttDialog from './widgets/EditMqttDialog.vue'
  import WebSocketDialog from './widgets/WebSocketDialog.vue'
  import DatabaseDialog from './widgets/DatabaseDialog.vue'
  import EditExcelDialog from './widgets/EditExcelDialog.vue'
  import EditKafkaDialog from './widgets/EditKafkaDialog.vue'
  import EditFtpDialog from './widgets/EditFtpDialog.vue'
  
  import EditHttpDrawer from "./widgets/EditHttpDrawer.vue";
  import EditMqttDrawer from "./widgets/EditMqttDrawer.vue";
  import EditDatabaseDrawer from "./widgets/EditDatabaseDrawer.vue";
  
  
  import EditHikvisionHttpDrawer from "./widgets/EditHikvisionHttpDrawer.vue";
  // import HTTPDataProcessDrawer from "@/components/DataWorkflow/HTTPDataProcessDrawer.vue";
  
  
  import type { FormRules } from 'element-plus'
  import ArtButtonTable from '@/components/core/forms/ArtButtonTable.vue'
  import { DatasourceConfigService } from '@/api/data-collection/datasourceConfig'
  import { RoleService } from '@/api/sys/roleApi'
  import { OrgService } from '@/api/sys/orgApi'
  import { RuleService } from '@/api/data-rule/ruleApi'
  import ArtRuleTable from '@/components/custom/table/ArtRuleTable.vue'
  import ArtRuleForm from '@/components/custom/forms/ArtRuleForm.vue'
  import ArtRuleSearchForm from '@/components/custom/forms/ArtRuleSearchForm.vue'
  import { useCommon } from '@/composables/useCommon'
 import { ref ,onMounted,reactive} from 'vue-demi'
 import { getCssVar,loadingService } from '@/utils/ui'
 
  const { containerMinHeight } = useCommon()
  const { width } = useWindowSize()
  defineOptions({ name: 'Collector' }) // 定义组件名称，用于 KeepAlive 缓存控制


	const mqttDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const httpDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const webSocketDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const databaseDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const excelDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const kafkaDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	const ftpDialog=ref({
		visible:false,
		type:'add',
		data:null
	})
	
	
	const editHttpDrawerRef = ref();
	const editMqttDrawerRef = ref();
	const editDatabaseDrawerRef = ref();
	
	const httpDataProcessDrawerRef = ref();
	const editHikvisionHttpDrawerRef = ref();
	

  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const loading = ref(false)

  // 响应式表单数据
  const formFilters = reactive({})

  // 选中的行数据
  const selectedRows = ref<any[]>([])
  // 重置表单
  const handleReset = () => {
	if(dataSourceConfigSearchFormRef.value){
		dataSourceConfigSearchFormRef.value.resetForm();
		Object.assign(formFilters, { ...dataSourceConfigSearchFormRef.value.getFormData() })
		dataSourceConfigTableRef.value.reset(formFilters)
	}
  }

  const handleSearch = () => {
	if(dataSourceConfigSearchFormRef.value){
		dataSourceConfigSearchFormRef.value.resetForm();
		Object.assign(formFilters, { ...dataSourceConfigSearchFormRef.value.getFormData() })
		dataSourceConfigTableRef.value.reset(formFilters)
	}
  }

const getTagType = (status: boolean) => {
	return status?'success':'danger'
}

// 构建标签文本
const buildTagText = (status: boolean) => {
	return status?'启用':'禁用'
}
  
  const dataSourceConfigSearchFormRef=ref();
  const dataSourceConfigTableRef=ref();
  // 处理表格行选择变化
  const handleSelectionChange = (selection: any[]) => {
    selectedRows.value = selection
  }
  /**
   * 规则实现
   */
  const fetchData = async (): Promise<any[]> => {
    return DatasourceConfigService.pages({
  		query:formFilters,
		pageNumber:dataSourceConfigTableRef.value.pageNumber,
		pageSize:dataSourceConfigTableRef.value.pageSize,
      })
  }
  
  const customFormatters = {
    status: (_value:any,row:any) => {
      return h(ElTag, { type: getTagType(row.status) }, () => buildTagText(row.status))
    },
	operate: (_value:any,row: any) => {
	  return h('div', [
	    h(ArtButtonTable, {
	      type: 'edit',
		  tip:true,
		  tipContent:'编辑',
	      onClick: () => openDialog('edit',row.type, row)
	    }),
	    h(ArtButtonTable, {
	      type: 'delete',
		  tip:true,
		  tipContent:'删除',
	      onClick: () => deleteRow(row)
	    })
	  ])
	}
  }
  
  
  
  
	const getToolBarFormatters = [
	   {
			type: 'add',
			tip:true,
			tipContent:'新增HTTP采集配置',
			text:'HTTP',
			onClick: () => openDialog('add','HTTP')
	   },
	   {
			type: 'add',
			tip:true,
			tipContent:'新增MQTT采集配置',
			text:'MQTT',
			onClick: () => openDialog('add','MQTT')
	   },
	   {
			type: 'add',
			tip:true,
			tipContent:'新增WebSocket采集配置 openWebSocketDialog',
			text:'WebSocket',
			onClick: () => openDatabaseDialog('add')
	   },
	   {
			type: 'add',
			tip:true,
			text:'数据库',
			tipContent:'新增关系型数据库采集配置', 
			onClick: () =>openDialog('add','DATABASE')
	   },
	   {
			type: 'add',
			tip:true,
			text:'Excel',
			tipContent:'新增Excel采集配置',
			onClick: () => openExcelDialog('add')
	   },
	   {
			type: 'add',
			tip:true,
			text:'Kafka',
			tipContent:'新增Kafka采集配置',
			onClick: () => openKafkaDialog('add')
	   },
	   {
			type: 'add',
			tip:true,
			text:'FTP',
			tipContent:'新增FTP采集配置',
			onClick: () => openFtpDialog('add')
	   }
	]
	
  const getFetchDatas = {
    roles: async (): Promise<any[]> => {
		return await RoleService.options({})
	},
	orgId:async (): Promise<any[]> => {
		return await OrgService.options({})
	}
  }
  
  const deleteRow =  (row:any) => {
  	ElMessageBox.confirm('确定删除【'+row.name+'】配置信息吗？', '删除提示', {
  		confirmButtonText: '确定',
  		cancelButtonText: '取消',
  		type: 'error'
  	}).then(async () => {
  		loading.value = true
  		try {
  			await DatasourceConfigService.delete(row.id);
  			ElMessage.success('成功')
			dataSourceConfigTableRef.value.reload()
  		} catch{
  		}finally{
  			loading.value = false
  		}
  	})
  }
  
const handleSubmit = async () => {
}
  
	// 对话框关闭
	const handleDialogClosed = () => {
		dialogVisible.value=false;
		dataSourceConfigTableRef.value.reload();
	};
	
	const openDialog = async (type: string, dsType:string,row?: any) => {
		if(row){
			loadingService.showLoading();
			try{
				const data= await DatasourceConfigService.get(row.id);
				openDrawer(type, dsType,data)
			}catch(err:any){
				console.error(err)
			}finally{
				loadingService.hideLoading()
			}
		}else{
			openDrawer(type, dsType,row)
		}
	}
	
	const openDrawer=(type: string, dsType:string,row?: any)=>{
		if('HTTP'==dsType){
			dialogVisible.value=true;
			nextTick(()=>{
				editHttpDrawerRef.value.openDialog(type,row)
			})
		}
		else if('MQTT'==dsType){
			dialogVisible.value=true;
			nextTick(()=>{
				editMqttDrawerRef.value.openDialog(type,row)
			})
		}
		else if('DATABASE'==dsType){
			dialogVisible.value=true;
			nextTick(()=>{
				editDatabaseDrawerRef.value.openDialog(type,row)
			})
		}
	}
	
	const openMqttDialog = async (type: string, row?: any) => {
		mqttDialog.value.visible = true
		mqttDialog.value.type = type
		mqttDialog.value.data=row||{};
	}
	
	const openWebSocketDialog = async (type: string, row?: any) => {
		webSocketDialog.value.visible = true
		webSocketDialog.value.type = type
		webSocketDialog.value.data=row||{};
	}	
	
	const openDatabaseDialog = async (type: string, row?: any) => {
		databaseDialog.value.visible = true
		databaseDialog.value.type = type
		databaseDialog.value.data=row||{};
	}
	
	const openExcelDialog = async (type: string, row?: any) => {
		excelDialog.value.visible = true
		excelDialog.value.type = type
		excelDialog.value.data=row||{};
	}
	
	const openKafkaDialog = async (type: string, row?: any) => {
		kafkaDialog.value.visible = true
		kafkaDialog.value.type = type
		kafkaDialog.value.data=row||{};
	}
	
	const openFtpDialog = async (type: string, row?: any) => {
		ftpDialog.value.visible = true
		ftpDialog.value.type = type
		ftpDialog.value.data=row||{};
	}
	
	onMounted(() => {
	})
</script>

<style lang="scss" scoped>
  .account-page {
    :deep(.user) {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
      }
    }
  }
</style>
